package ws

import (
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"regexp"
	"shi_project/main/communicate"
	"strings"
)

func transformMessage(s string) (key string, val string) {
	fmt.Println("s=", s)
	re := regexp.MustCompile(`\s\d{13}\s`)
	arr := re.FindStringSubmatchIndex(s)
	name := s[:arr[0]]
	val = s[arr[1]:]
	time := re.FindStringSubmatch(s)
	time = strings.Fields(time[0])
	key = name + "-" + time[0]
	return key, val
}

func Chating(w http.ResponseWriter, r *http.Request) {
	var upgrader = websocket.Upgrader{
		CheckOrigin: func(r *http.Request) bool {
			return true
		},
		Subprotocols: []string{r.Header.Get("Sec-WebSocket-Protocol")},
	}
	conn, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
		log.Print("Error during connection upgradation:", err)
		return
	}
	po := communicate.Pool.Get() //从连接池，取一个链接
	defer po.Close()        //函数运行结束 ，把连接放回连接池

	communicate.Conns = append(communicate.Conns, conn)
	defer conn.Close()
	for {
		messageType, message, err := conn.ReadMessage()
		if err != nil {
			log.Println("Error during message reading:", err)
			for i := 0; i < len(communicate.Conns); i++ {
				if communicate.Conns[i] == conn {
					communicate.Conns = append(communicate.Conns[0:i], communicate.Conns[i+1:]...)
					break
				}
			}
			break
		}
		// 把聊天记录存储在ｒｅｄｉｓ中
		k, v := transformMessage(string(message))
		_, err = po.Do("setex", k, "600", v)
		if err != nil {
			fmt.Println("聊天存入redis失败", err)
		}
		log.Printf("messageType: %v\n", messageType)
		for _, v := range communicate.Conns {
			if v != conn {
				err = v.WriteMessage(messageType, message)
				if err != nil {
					log.Println("Error during message writing:", err)
				}
			}
		}
	}
}
